//
//  DatabaseViewController.m
//  MoXiProject
//
//  Created by 周筱雯 on 2017/7/19.
//  Copyright © 2017年 周筱雯. All rights reserved.
//

#import "DatabaseViewController.h"
#import "IntegralViewCell.h"


static  int leagueIdStr = 0;

@interface DatabaseViewController ()
<
    UITableViewDataSource,
    UITableViewDelegate
>
{
    UIView *viewHeaderTop;
    UIButton *button;
    UIButton *selectedBtn;
    BOOL clicked;
}

@property (nonatomic, copy) UITableView *tabView;
@property (nonatomic, copy) NSMutableArray *dataSourceArr;

@property (nonatomic, copy) NSString *yesorNo;
@end

@implementation DatabaseViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    [self.view setBackgroundColor:[UIColor whiteColor]];
    [self.navigationItem setTitle:@"资料库"];
    
    
    
    _dataSourceArr = [NSMutableArray new];
    viewHeaderTop = [[UIView alloc] initWithFrame:CGRectMake(0, 0, DEF_DEVICE_WIDTH, 28 * Heigt_P)];
    viewHeaderTop.backgroundColor = [UIColor clearColor];
    [self.view addSubview:viewHeaderTop];
    clicked = false;
    NSArray * titleArr = @[@"西甲",@"英超", @"德甲", @"欧冠", @"意甲", @"法甲"];
    
    for (int i = 0; i < titleArr.count; i++) {
        button = [UIButton buttonWithType:UIButtonTypeCustom];
        button.frame =  CGRectMake(((viewHeaderTop.frame.size.width - 7) / 6 + 1) * i + 1,0, (viewHeaderTop.frame.size.width - 7) / 6, viewHeaderTop.frame.size.height);
        [button setTitle:titleArr[i] forState:UIControlStateNormal];
        button.backgroundColor = Guoguo_darkGreyFontColor;
        button.tag = 78 + i;
        if (button.tag == 83 && !clicked) {
            
        }
        [button addTarget:self action:@selector(changeLeagueId:) forControlEvents:UIControlEventTouchUpInside];
        
        [viewHeaderTop addSubview:button];
    }
    leagueIdStr = 7;
    [self loadInterRanking:leagueIdStr];
    [self setupUI];

}

- (void)setupUI {
    _tabView = [[UITableView alloc] initWithFrame:CGRectMake(0, CGRectGetMaxY(viewHeaderTop.frame), self.view.frame.size.width, DEF_CONTENT_INTABBAR_HEIGHT - 28)];
    _tabView.showsVerticalScrollIndicator = false;
    _tabView.delegate = self;
    _tabView.dataSource = self;
    _tabView.backgroundColor = Guoguo_backgroundColor;
    _tabView.separatorStyle = UITableViewCellSeparatorStyleNone;
    [self setExtraCellLineHidden:_tabView];
    [self.view addSubview:_tabView];
}

//多余的空行上不显示分割线
- (void)setExtraCellLineHidden: (UITableView *)tableView{
    UIView *view =[ [UIView alloc]init];
    view.backgroundColor = [UIColor clearColor];
    [tableView setTableFooterView:view];
    [tableView setTableHeaderView:view];
}

- (void)loadInterRanking:(int)leagueIdStrs {
    
    leagueIdStr = leagueIdStrs;
    
    [MXUtility showMBProgress:self.view message:LoadingText];
    
    
    NSString *str = [NSString stringWithFormat:@"%d",leagueIdStr];
    
    
    [self getBaseInfoParameter:@{@"leagueId":str}];
}

- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];

}


- (void)updateUIAfterCallInterRanking:(NSDictionary *)dic {
    
    [MXUtility hideMBProgress:self.view];
    
    [self.dataSourceArr removeAllObjects];
    [self.dataSourceArr addObjectsFromArray:[[[dic objectForKey:@"standings"] objectAtIndex:0] objectForKey:@"teamInfo"]];
    [_tabView reloadData];
}

#pragma mark -- UITableViewDelegate &  UITableViewDatasource

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    return (DEF_CONTENT_INTABBAR_HEIGHT) / 16;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    
    return _dataSourceArr.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    static NSString *cellIdentifier = @"cell";
    IntegralViewCell *cell = [tableView cellForRowAtIndexPath:indexPath];
    if (cell == nil) {
        cell = [[IntegralViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellIdentifier];
    }
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    NSInteger curRow = [indexPath row];
    NSDictionary *main = [_dataSourceArr objectAtIndex:curRow];
    cell.lblRank.text = [NSString stringWithFormat:@"%@", [main objectForKey:@"rank"]];
    cell.lblTeam.text = [NSString stringWithFormat:@"%@", [main objectForKey:@"team"]];//
    cell.lblMatchesPlayed.text = [NSString stringWithFormat:@"%@", [main objectForKey:@"matchesPlayed"]];
    cell.lblWins.text = [NSString stringWithFormat:@"%@",[main objectForKey:@"wins"]];
    cell.lblDraws.text = [NSString stringWithFormat:@"%@", [main objectForKey:@"draws"]];
    cell.lblLosses.text =  [NSString stringWithFormat:@"%@", [main objectForKey:@"losses"]];
    cell.lblPoints.text = [NSString stringWithFormat:@"%@", [main objectForKey:@"points"]];
    cell.backgroundColor = [UIColor UIColorFromRGB:0xFFFF9F alpha:1];
    return cell;
}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
    
    CGFloat border = 1.0f;
    UIView *viewHeader = [[UIView alloc] initWithFrame:CGRectMake(0, 0, DEF_DEVICE_WIDTH, DEF_DEVICE_HEIGHT / 12)];
    viewHeader.backgroundColor = [UIColor whiteColor];
    
    UILabel * _lblRank = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, (viewHeader.frame.size.width - border * 6) / 8, viewHeader.frame.size.height)];
    _lblRank.text = @"排名";
    _lblRank.textAlignment = NSTextAlignmentCenter;
    [_lblRank setFont:[UIFont boldSystemFontOfSize:16.0]];
    _lblRank.textColor = Guoguo_hintFontColor;
    [viewHeader addSubview:_lblRank];
    
    UILabel * _lblTeam = [[UILabel alloc] initWithFrame:CGRectMake(_lblRank.frame.origin.x + _lblRank.frame.size.width + border, _lblRank.frame.origin.y, (viewHeader.frame.size.width - border * 6) * 2 / 8, viewHeader.frame.size.height)];
    _lblTeam.text = @"球队";
    _lblTeam.textAlignment = NSTextAlignmentCenter;
    [_lblTeam setFont:[UIFont boldSystemFontOfSize:16.0]];
    _lblTeam.textColor = Guoguo_hintFontColor;
    [viewHeader addSubview:_lblTeam];
    
    UILabel * _lblMatchesPlayed = [[UILabel alloc] initWithFrame:CGRectMake(_lblTeam.frame.origin.x + _lblTeam.frame.size.width + border, _lblTeam.frame.origin.y, _lblRank.frame.size.width, viewHeader.frame.size.height)];
    _lblMatchesPlayed.text = @"已赛";
    _lblMatchesPlayed.textAlignment = NSTextAlignmentCenter;
    [_lblMatchesPlayed setFont:[UIFont boldSystemFontOfSize:16.0]];
    _lblMatchesPlayed.textColor = Guoguo_hintFontColor;
    [viewHeader addSubview:_lblMatchesPlayed];
    
    UILabel * _lblWins = [[UILabel alloc] initWithFrame:CGRectMake(_lblMatchesPlayed.frame.origin.x + _lblMatchesPlayed.frame.size.width + border, _lblMatchesPlayed.frame.origin.y, _lblMatchesPlayed.frame.size.width, viewHeader.frame.size.height)];
    _lblWins.text = @"胜";
    _lblWins.textAlignment = NSTextAlignmentCenter;
    [_lblWins setFont:[UIFont boldSystemFontOfSize:16.0]];
    _lblWins.textColor = Guoguo_hintFontColor;
    [viewHeader addSubview:_lblWins];
    
    UILabel * _lblDraws = [[UILabel alloc] initWithFrame:CGRectMake(_lblWins.frame.origin.x + _lblWins.frame.size.width + border, _lblWins.frame.origin.y, _lblWins.frame.size.width, viewHeader.frame.size.height)];
    _lblDraws.text = @"平";
    _lblDraws.textAlignment = NSTextAlignmentCenter;
    [_lblDraws setFont:[UIFont boldSystemFontOfSize:16.0]];
    _lblDraws.textColor = Guoguo_hintFontColor;
    [viewHeader addSubview:_lblDraws];
    
    UILabel * _lblLosses = [[UILabel alloc] initWithFrame:CGRectMake(_lblDraws.frame.origin.x + _lblDraws.frame.size.width + border, _lblDraws.frame.origin.y, _lblDraws.frame.size.width, _lblDraws.frame.size.height)];
    _lblLosses.text = @"负";
    _lblLosses.textAlignment = NSTextAlignmentCenter;
    [_lblLosses setFont:[UIFont boldSystemFontOfSize:16.0]];
    _lblLosses.textColor = Guoguo_hintFontColor;
    [viewHeader addSubview:_lblLosses];
    
    UILabel * _lblPoints = [[UILabel alloc] initWithFrame:CGRectMake(_lblLosses.frame.origin.x + _lblLosses.frame.size.width + border, _lblLosses.frame.origin.y, _lblLosses.frame.size.width, _lblLosses.frame.size.height)];
    _lblPoints.text = @"积分";
    _lblPoints.textAlignment = NSTextAlignmentCenter;
    viewHeader.backgroundColor = [UIColor UIColorFromRGB:0xFFE2D7 alpha:1];
    [_lblPoints setFont:[UIFont boldSystemFontOfSize:16.0]];
    _lblPoints.textColor = Guoguo_hintFontColor;
    [viewHeader addSubview:_lblPoints];
    
    return viewHeader;
}
- (void)changeLeagueId:(UIButton *)sender {
    //    sender.enabled = NO;
    //    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(5 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
    //        sender.enabled = YES;
    //    });
    clicked = true;
    if (clicked) {
        [button setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
        [selectedBtn setBackgroundColor:Guoguo_darkGreyFontColor];
    }
    if(selectedBtn == sender) {
        
        //上次点击过的按钮，不做处理
        //        [sender setTitleColor:Guoguo_darkGreyFontColor forState:UIControlStateNormal];
        //        [sender setBackgroundColor:Guoguo_hintFontColor];
    } else{
        //本次点击的按钮
        [sender setTitleColor:Guoguo_darkGreyFontColor forState:UIControlStateNormal];
        [sender setBackgroundColor:[UIColor yellowColor]];
        //将上次点击过的按钮
        [selectedBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
        [selectedBtn setBackgroundColor:Guoguo_darkGreyFontColor];
    }
    
    selectedBtn= sender;
    
    if (sender.tag == 78) {
        
        [self loadInterRanking:7];
    } else if (sender.tag == 79) {
        
        [self loadInterRanking:8];
    } else if (sender.tag == 80) {
        [self loadInterRanking:9];
        
    } else if (sender.tag == 81) {
        [self loadInterRanking:7];
        
    } else if (sender.tag == 82) {
        [self loadInterRanking:13];
        
    } else if (sender.tag == 83) {
        [self loadInterRanking:16];
        
    }
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    
    return (DEF_CONTENT_INTABBAR_HEIGHT) / 12;
}




- (void)getBaseInfoParameter:(NSDictionary *)parameter{
    
    //http://zx.caipiao.163.com/libraryapi/league_matchRank.html?leagueId=1
    
    
    NSString *url = [NSString stringWithFormat:@"http://zx.caipiao.163.com/libraryapi/league_matchRank.html?product=caipiao_client&mobileType=iphone&ver=4.32&channel=appstore&apiVer=1.1&apiLevel=27&deviceId=C70F3605-A233-4EDE-B6BA-DE00386793BD"];
    
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    manager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects: @"text/plain", nil];
    
    
    /*@"application/json", @"text/json", @"text/javascript",@"application/x-json",@"text/html",*/
    [manager GET:url parameters:parameter progress:nil success:^(NSURLSessionTask *task, id responseObject) {
        
        NSLog(@"获取资料库 = %@",responseObject);
        
//        dispatch_async(dispatch_get_main_queue(), ^{
        
        [self updateUIAfterCallInterRanking:responseObject];
        
//        });
        
        
        
        
        
    }  failure:^(NSURLSessionTask *operation, NSError *error) {
        
        [MXUtility hideMBProgress:self.view];
        NSLog(@"%@",error);
    }];
    
    
    
    
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
